/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.network;
import java.net.*;
import java.io.*;
import com.cse.p2p.common.*;
import com.cse.p2p.database.ServerDatabase;
import com.cse.p2p.parser.FileMetadata;
import server.dicfile.DicFileGenerating;
import com.cse.p2p.database.ServerDatabase.*;
import com.cse.p2p.hash.HashImplement;
import com.cse.p2p.hash.HashImplement.*;
import com.cse.p2p.localfile.LocalFile;
/**
 *
 * @author TuyetNgan
 */
public class ServerNetwork {

    private static Integer sizeOfDatabase = 10;
    private static String[] user_name = new String[sizeOfDatabase];
	public static class ServerTask extends Thread {

        private Socket socket = null;
        private PrintStream out = null;
        private BufferedReader in = null;
        private BufferedReader infromScreen = null;
        private ServerTask[] serverTask;
        private Integer ID;
        int defaultPortDataReceive = 2000;
        int defaultPortDataSend = 2001;
        private FileMetadata file_mete_data;
        private DicFileGenerating dic ;
		public ServerTask (Socket s, int id, ServerTask[] st) {
            this.socket = s;
            this.serverTask = st;
            this.ID = id;
		}
        public void  newChat(){
            try{
                out = new PrintStream(socket.getOutputStream());
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                infromScreen = new BufferedReader(new InputStreamReader(System.in));
            }
            catch(IOException e){}
        }
        public void closeConnection(){
            try {
                out.close();
                in.close();
                infromScreen.close();
                socket.close();
            }
            catch (IOException e){}

        }

		@Override
		public void run () {
			try {
                newChat();
                user_name[ID] = in.readLine();
                String mess;
                System.out.println(user_name[ID]);
				while ((mess = in.readLine()) != null) {
                    Message message = Message.fromString(mess);
                    int typeOfProtocol = message.getType();
                    String data = message.getData();
                    //System.out.println("Message : " + typeOfProtocol);
					switch (typeOfProtocol) {

                        // client get the list of all available pieces of a file
                        case Message.MsgType.REQ_FOR_AVAI_PIECES:
                        {
                            String fileID = data;
                            // call thread peer to collect info -> fileID
                            break;
                        }
                        // server collect the info of all available pieces of a file
                        case Message.MsgType.RES_VRF_ALL_PIECES:
                        {
                            String peer_info = data;
                            /* concatanate all peer online */
                                // TODO : Networking
                            /* return List<PeerInfo> */
                            break;
                        }

                        // client ask for the permision of uploading a file
                        case Message.MsgType.REQ_UP_HOST_FILE:
                        {
                            System.out.println("Client request up file");
                            file_mete_data = FileMetadata.fromString(data);
                            /* analyzing file */
                            // Call LocalFile to check Disk
                                // TO DO ...

                            while(true)
                            {
                                /* return a message to client to accept */
                                Message messSend = new Message("PUT","OK","OK");
                                out.println(messSend.toString());

                                /* create path file in Memory with RealName */
                                //example
                                File file_receive;
                                file_receive= new File("C://server/file_save.txt");
                                file_receive.createNewFile();

                                /* create thread receive file */
                                Thread t = new Thread(new ServerTaskData(file_receive));
                                t.start();
                                while(t.isAlive());

                                /* Check Hashfile */
                                if(HashImplement.compareHash(file_mete_data.getFileHash(),
                                        HashImplement.getHashFile(file_receive)))
                                {
                                    System.out.println("Hash check pass!");
                                    /* create DicFile */
                                    String file_name = file_mete_data.getFileName();
                                    dic = new DicFileGenerating();
                                    int fileID = com.cse.p2p.database.ServerDatabase.createNewFileAndReturnFileID(
                                            file_name,
                                            file_name+ServerDatabase.countSameFileName(file_name)+1,
                                            file_mete_data.getFileSize(),
                                            LocalFile.writeFiletoDisk(file_receive),
                                            file_mete_data.getFileDesc(),
                                            this.socket.getRemoteSocketAddress().toString());

                                    dic.run(file_receive,fileID, file_mete_data.getFileName(),
                                            file_mete_data.getFileDesc() ,
                                            this.socket.getRemoteSocketAddress().toString(),
                                            this.socket.getLocalAddress().toString());


                                    /* send and wait for signal from client accept DicFile */
                                    Message messSend2 = new Message("GET", "UP","DIC");
                                    out.println(messSend2.toString());
                                    break;
                                }
                                else{
                                    System.out.println("An error occurs when you transfer! PLease, send again!");
                                }
                            }
                            break;
                        }

                        // client response receive message upload file is finished
                        case Message.MsgType.RES_UP_DIC_FILE:
                        {
                             if(data.equals("OK")){
                                System.out.println("Client response OK");
                                /* send DicFile back to client */
                                //dic.getPath
                                //example
                                File dicf = new File("C://dicfile.txt");
                                Thread t = new Thread(new SendData(dicf, defaultPortDataSend));
                                t.sleep(1000);
                                t.start();
                                while(t.isAlive());
                            }
                            else if(data.equals("NONE")){
                                // never happen this case
                                System.out.println("Send again!");

                            }
                            else{ // error
                                System.out.println("ERROR : RES_UP_DIC_FILE");
                            }
                            break;
                        }

                        // client response for the dicfile transfering
                        case Message.MsgType.RES_FILE_TRANSFER:
                        {

                            if(data.equals("OK")){
                                System.out.print("Finish!");
                            }
                            else if(data.equals("NONE")){
                                /* remember client didnot receive dicfile */
                                /* if client online , send again*/

                                /* send and wait for signal from client accept DicFile */
                                Message messSend2 = new Message("GET", "UP","DIC");
                                out.println(messSend2.toString());
                            }
                            else{
                                System.out.println("ERROR : RES_FILE_TRANSFER");
                            }
                            break;
                        }


					}
				}
			}
			catch (Exception exc) {}
		}
	}



}
